package com.pms.controller;

import com.pms.constant.JwtClaimsConstant;
import com.pms.constant.MessageConstant;
import com.pms.dto.*;
import com.pms.entity.User;
import com.pms.exception.AccountNotFoundException;
import com.pms.properties.JwtProperties;
import com.pms.result.PageResult;
import com.pms.result.Result;
import com.pms.service.UserService;
import com.pms.utils.JwtUtil;
import com.pms.vo.UserInfoVO;
import com.pms.vo.UserLoginVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户相关接口
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    @ApiOperation(value = "登录", httpMethod = "POST")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("登录：{}",userLoginDTO);
        User user=userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .phone(user.getPhone())
                .roles(Collections.singletonList(user.getRoles()))
                .avatar(user.getAvatar())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 获取登录的用户信息
     * @param token
     * @return
     */
    @GetMapping("/info")
    @ApiOperation("获取登录的用户信息")
    public Result<UserInfoVO> info(String token){
        log.info("获取登录的用户信息:{}",token);

        // 验证和解析 JWT
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token);
        if (claims == null) {
            throw new AccountNotFoundException(MessageConstant.ID_NOT_EXIST);
        }

        // 从 claims 中获取用户 ID
        Integer userId = (Integer) claims.get(JwtClaimsConstant.USER_ID);
        User user = userService.getById(userId);

        if (user == null) {
            throw  new AccountNotFoundException(MessageConstant.USER_NOT_EXIST);
        }

        UserInfoVO userInfoVO=UserInfoVO.builder()
                .id(user.getId())
                .name(user.getUsername())
                .avatar(user.getAvatar())
                .phone(user.getPhone())
                .roles(Collections.singletonList(user.getRoles()))
                .build();
        return Result.success(userInfoVO);
    }

    /**
     * 登出
     * @return
     */
    @ApiOperation(value = "登出", httpMethod = "POST")
    @PostMapping("/logout")
    public Result<String> logout(){
        return Result.success();
    }

    /**
     *注册
     * @param userRegisterDTO
     * @return
     */
    @ApiOperation(value = "注册", httpMethod = "POST")
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserRegisterDTO userRegisterDTO){
        log.info("注册：{}",userRegisterDTO);
        userService.setUser(userRegisterDTO);
        return Result.success();
    }

    /**
     * 动态修改信息
     * @param userUpdateDTO
     * @return
     */
    @ApiOperation(value = "动态修改信息", httpMethod = "PUT")
    @PutMapping("/update")
    public Result<String> update(@RequestBody UserUpdateDTO userUpdateDTO){
        log.info("动态修改信息：{}",userUpdateDTO);
        userService.update(userUpdateDTO);
        return Result.success();
    }

    /**
     * 根据id查询信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询信息", httpMethod = "GET")
    @GetMapping("/list/{id}")
    public Result<User> getUserById(@PathVariable Integer id){
        log.info("根据id查询信息：{}",id);
        User user=userService.getUserById(id);
        return Result.success(user);
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @PutMapping("/update/password")
    @ApiOperation(value = "修改密码",httpMethod = "PUT")
    public Result<String> updatePassword(@RequestBody PasswordDTO passwordDTO){
        log.info("修改密码: {}",passwordDTO);
        userService.updatePassword(passwordDTO);
        return Result.success();
    }

    /**
     * 用户分页查询
     * @param userPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("用户分页查询")
    public Result<PageResult> page(UserPageQueryDTO userPageQueryDTO){
        log.info("用户分页查询,{}",userPageQueryDTO);
        PageResult pageResult=userService.page(userPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delete")
    @ApiOperation("批量删除")
    public Result<String> deleteBatch(@RequestParam List<Integer> ids){
        log.info("批量删除,{}",ids);
        userService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 管理员修改用户信息
     * @param userAdminUpdateDTO
     * @return
     */
    @PutMapping("/update/admin")
    @ApiOperation("管理员修改用户信息")
    public Result<String> updateByAdmin(@RequestBody UserAdminUpdateDTO userAdminUpdateDTO){
        log.info("管理员修改用户信息,{}",userAdminUpdateDTO);
        userService.updateByAdmin(userAdminUpdateDTO);
        return Result.success();
    }
}
